import { http } from '@/utils/http'
import { useUserStore } from '@/stores'

export const getPostListAPI = (params) => {
  return http({
    method: 'GET',
    url: '/forum/post',
    data: params,
  })
}

export const likePostAPI = (id) => {
  return http({
    method: 'POST',
    url: `/forum/post/like/${id}`,
  })
}

export const getUserAllPostAPI = () => {
  return http({
    method: 'GET',
    url: `/forum/post/user`,
  })
}

export const getPostInfoAPI = (id) => {
  return http({
    method: 'GET',
    url: `/forum/post/comment/${id}`,
  })
}

export const deletePostAPI = (id) => {
  return http({
    method: 'DELETE',
    url: `/forum/post/${id}`,
  })
}

export const deleteCommentAPI = (id) => {
  return http({
    method: 'DELETE',
    url: `/forum/comment/${id}`,
  })
}

export const createComment = (params) => {
  return http({
    method: 'POST',
    url: `/forum/comment`,
    data: params,
  })
}

export const createPostAPI = (params) => {
  // 响应成功
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: '/forum/post',
      filePath: params.url,
      name: 'file',
      formData: {
        ...params,
      },
      success(res) {
        console.log(res)
        // 状态码 2xx，参考 axios 的设计
        const result = JSON.parse(res.data)
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (result.code === 200) {
            return resolve(result)
          }
          if (result.code >= 2000 && result.code <= 2011) {
            //账号问题
            //清理用户信息，跳转到登录页
            const userStore = useUserStore()
            userStore.removeToken()
            userStore.setUser({})
            uni.showToast({
              icon: 'none',
              title: result.msg || '请求错误',
            })
            setTimeout(() => {
              uni.navigateTo({ url: '/pages/login/login' }) //关闭当前页面 重定向到登录页
            }, 1500)
          }
          //其他问题 直接提示框告知用户即可
          uni.showToast({
            icon: 'none',
            title: result.msg || '请求错误',
          })
          return reject(res)
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          uni.showToast({
            icon: 'none',
            title: result.msg || '请求错误',
          })
          return reject(res)
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
        })
        return reject(err)
      },
    })
  })
}
